<template>
  <!-- 情况一：添加/修改 -->
  <el-tab-pane
    v-for="(item, index) in formData!.skus!"
    :key="index"
    :label="item.tabsName"
    :name="item.tabsName"
  >
    <div>
      <el-form-item
        label="图片"
        class="w-480px!"
        :prop="`skus[${index}][picUrl]`"
        :rules="rules.picUrl"
      >
        <UploadImg v-model="item.picUrl" :showDelete="!isDetail" height="50px" width="50px" />
      </el-form-item>
    </div>
    <div class="flex flex-wrap">
      <el-form-item
        label="有效期"
        :prop="`skus[${index}][expiryDate]`"
        :rules="rules.expiryDate"
        class="w-480px!"
      >
        <el-input v-model="item.expiryDate">
          <template #append>
            <el-select v-model="item.expiryDateUnit" class="w-80px!">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.DATE_INTERVAL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="零售价"
        class="w-480px!"
        :prop="`skus[${index}][price]`"
        :rules="rules.price"
      >
        <el-input
          v-model="item.price"
          class="w-100%!"
          :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
        >
          <template #append>
            <span>元</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="好友礼遇"
        class="w-480px!"
        :prop="`skus[${index}][friendTesyNum]`"
        :rules="rules.friendTesyNum"
      >
        <el-input v-model="item.friendTesyNum" :formatter="verifiyNumberInteger" class="w-100%!">
          <template #append> 次 </template>
        </el-input>
      </el-form-item>
    </div>
    <!-- 商品折扣 -->
    <div>
      <el-form-item label="商品折扣">
        <div>
          <el-checkbox-group v-model="item.useDiscountType">
            <template
              v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_USE_DISCOUNT_TYPE)"
              :key="dict.value"
            >
              <el-checkbox
                :value="dict.value"
                v-if="dict.value == 0"
                :disabled="item.useDiscountType?.includes(1) || item.useDiscountType?.includes(2)"
              >
                {{ dict.label }}
              </el-checkbox>
              <el-checkbox :value="dict.value" v-else :disabled="item.useDiscountType?.includes(0)">
                {{ dict.label }}
              </el-checkbox>
            </template>
          </el-checkbox-group>

          <Explaintip :msg="'折扣类型优先级： 指定商品 > 指定类型 > 全部商品'" />
        </div>
      </el-form-item>
      <el-form-item label="折扣比例" class="w-480px!" v-if="item.useDiscountType?.includes(0)">
        <el-input
          v-model="item.allDiscount"
          :formatter="(value: string) => verifyNumberPercentage(value)"
          class="w-100%!"
        >
          <template #append>
            <span>%</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="商品类型" class="w-480px!" v-show="item.useDiscountType?.includes(1)">
        <ProductSpuTypeSelect
          ref="SpuTypeSelectRef"
          v-model="item.typeDiscountGoods"
          @change="
            (e) => {
              typeDiscountGoodsChange(e, index)
            }
          "
        />
      </el-form-item>
      <el-form-item
        label=""
        v-if="
          item?.typeDiscountGoods &&
          item.typeDiscountGoods?.length > 0 &&
          item.useDiscountType?.includes(1)
        "
      >
        <div class="flex flex-wrap">
          <div
            v-for="(typeDiscountItem, typeDiscountItemIndex) in item.typeDiscountGoods"
            :key="typeDiscountItemIndex"
          >
            <el-table border :data="[typeDiscountItem]">
              <el-table-column label="商品类型" align="center" min-width="168">
                <template #default="scope">
                  <span>{{ getSputTypeInfo(scope.row, index) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="折扣比例" align="center" min-width="168">
                <template #default="scope">
                  <el-form :model="item.appointTypeDiscount[scope.row]" :disabled="isDetail">
                    <el-form-item prop="discountRatio">
                      <el-input
                        v-model.number="item.appointTypeDiscount[scope.row].discount"
                        :formatter="(value: string) => verifyNumberPercentage(value)"
                        placeholder="请输入"
                      >
                        <template #append>
                          <span>%</span>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="指定商品" v-if="item.useDiscountType?.includes(2)">
        <GiveGoodsForm
          v-model="item.appointSkusDiscount"
          :scene-type="'discount'"
          :rule-config="goodsDiscountruleConfig"
          ref="discountGiveGoodsFormRef"
          :is-detail="isDetail"
          @error-info="setgiveGoodsFormErrorInfo"
        />
      </el-form-item>
    </div>
    <!-- 积分规则 -->
    <div class="">
      <el-form-item label="积分规则" prop="consumerMoney" class="w-480px!">
        消费
        <el-input-number
          v-model="item.consumerMoney as number"
          :precision="2"
          :controls="false"
          class="w-30! mx-5px border-none!"
        />
        元 &nbsp;,&nbsp;
        <el-form-item prop="consumerPoints">
          积
          <el-input-number
            v-model="item.consumerPoints"
            :precision="0"
            :controls="false"
            class="w-30! mx-5px"
          />
          分
        </el-form-item>
      </el-form-item>
      <el-form-item prop="rechargeMoney">
        充值
        <el-input-number
          v-model="item.rechargeMoney as number"
          :precision="2"
          :controls="false"
          class="w-30! mx-5px border-none!"
        />
        元 &nbsp;,&nbsp;
        <el-form-item prop="rechargePoints">
          积
          <el-input-number
            v-model="item.rechargePoints"
            :precision="0"
            :controls="false"
            class="w-30! mx-5px"
          />
          分
        </el-form-item>
      </el-form-item>
      <!-- 关联商品 -->
      <el-form-item label="关联商品">
        <GiveGoodsForm
          :scene-type="'number'"
          v-model="item.appointSkusCount"
          :rule-config="giveGoodsruleConfig"
          ref="GiveGoodsFormRef"
          @error-info="setgiveGoodsFormErrorInfo"
        />
      </el-form-item>
      <el-form-item label="月赠送券">
        <div>
          <el-radio-group
            v-model="item.memberMonthlyCouponType"
            @change="monthGiveTypeChange(item)"
          >
            <el-radio :value="0">统一设置</el-radio>
            <!-- <el-radio :value="1">单一设置</el-radio> -->
          </el-radio-group>
          <Explaintip
            v-if="item.memberMonthlyCouponType == 0"
            msg="赠送的有效期为客户付费会员的有效期，到账日期当日如客户付费会员状态为有效时，均会赠送代金券。赠送的券和数量均以赠送券中关联的券和数量为基础，每月循环，请谨慎设置！"
          />
          <Explaintip
            v-if="item.memberMonthlyCouponType == 1"
            msg="可以针对不同时间设置不同的券和数量，如需要个性化赠送券，需使用此配置。某个到账时间不赠送券时，不添加券即可，即当月不会赠送代金券。"
          />
        </div>
      </el-form-item>
      <el-form-item label="赠送日期" class="w-480px!" v-if="item.memberMonthlyCouponType == 0">
        <el-select v-model="item.bonusDays" placeholder="赠送日期" class="w-100%">
          <el-option
            v-for="(item, index) in monthGiveRollDateOptions"
            :key="index"
            :value="item.value"
            >{{ item.label }}</el-option
          >
        </el-select>
      </el-form-item>

      <el-form-item label="赠送券" v-if="item.memberMonthlyCouponType == 0">
        <div class="w-100%!">
          <GiveCouponSelect ref="GiveCouponSelectRef" v-model="item.appointSkusCoupon" />
        </div>
      </el-form-item>
      <!-- <el-form-item label="单一设置" v-if="item.memberMonthlyCouponType == 1">
        <div class="w-100%">
          <el-button @click="monthGiveTypeAdd(item.monthlyGiveCoupon)"> 新增 </el-button>
          <el-table class="mt20px" border :data="item.monthlyGiveCoupon" default-expand-all>
            <el-table-column type="expand">
              <template #default="scope">
                <CouponList
                  v-if="scope.row!.skuCoupon"
                  v-model:multiple-selection="scope.row!.skuCoupon"
                  :is-detail="isDetail"
                >
                  <template #extension>
                    <el-table-column align="center" label="关联数量" prop="number" min-width="168">
                      <template #default="{ row }">
                        <el-input-number
                          v-model="row.number"
                          :disabled="isDetail"
                          :min="1"
                          :precision="0"
                          :step="1"
                          class="w-120px!"
                          controls-position="right"
                        />
                      </template>
                    </el-table-column>
                  </template>
                </CouponList>
              </template>
            </el-table-column>
            <el-table-column label="赠送时间" :align="'center'" min-width="168">
              <template #default="{ row }">
                <span
                  >购买后第
                  <el-input-number
                    v-model="row.intoAccountDateMonth"
                    :precision="0"
                    :step="1"
                    placeholder="X"
                    :controls="false"
                    class="w-60px!"
                  />个月</span
                >
              </template>
            </el-table-column>
            <el-table-column min-width="168" :align="'center'" label="赠送日期">
              <template #default="{ row }">
                <el-form-item>
                  <el-input-number
                    v-model="row.intoAccountDateDay"
                    :precision="0"
                    :step="1"
                    :min="1"
                    :max="31"
                    placeholder="日期"
                    class="w-100%!"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column min-width="168" :align="'center'" label="赠送券明细">
              <template #default="{ row }">
                <el-button @click="selectCoupon(row, 'skuCoupon')">添加券</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="操作" :align="'center'" width="120">
              <template #default="{ $index }">
                <el-button
                  text
                  type="primary"
                  @click="monthGiveTypeDelete(item.monthlyGiveCoupon, $index)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item> -->
      <el-form-item label="生日券">
        <div class="w-100%">
          <GiveCouponSelect
            ref="GiveBrithdayCouponSelectRef"
            v-model="item.appointSkusBirthdayCoupon"
          />
        </div>
      </el-form-item>

      <el-form-item label="商城包邮" prop="isPostageCost">
        <el-switch v-model="item.isPostageCost" />
      </el-form-item>
      <el-form-item label="赠送积分" prop="bonusPoints">
        <el-input-number
          v-model="item.bonusPoints"
          :min="0"
          :precision="0"
          placeholder="请输入赠送积分"
          class="w-80!"
        />
      </el-form-item>
    </div>
  </el-tab-pane>
</template>
<script lang="ts" setup>
import { PropType, Ref } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { UploadImg } from '@/components/UploadFile'
import type { Property, Sku, Spu } from '@/api/mall/product/spu'
import {
  RuleConfig,
  PropertyAndValues,
  ProductSpuTypeSelect
} from '@/views/mall/product/spu/components/index'
import { ElTable } from 'element-plus'
import { isEmpty } from '@/utils/is'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import GiveGoodsForm from '@/views/mall/product/spuPaidMember/components/GiveGoodsForm.vue'
import GiveCouponSelect from '@/views/mall/product/spuPaidMember/components/GiveCouponSelect.vue'
import {
  verifyNumberIntegerAndFloat,
  verifyNumberPercentage,
  verifiyNumberInteger
} from '@/utils/formatter'
import { generateNumericUUID } from '@/utils'

defineOptions({ name: 'SkuList' })
const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  propFormRules: {
    type: Object as any,
    default: () => {}
  },
  propertyList: {
    type: Array as PropType<PropertyAndValues[]>,
    default: () => []
  },
  ruleConfig: {
    type: Array as PropType<RuleConfig[]>,
    default: () => []
  },

  isBatch: propTypes.bool.def(false), // 是否作为批量操作组件
  isDetail: propTypes.bool.def(false), // 是否作为 sku 详情组件
  isComponent: propTypes.bool.def(false), // 是否作为 sku 选择组件
  isActivityComponent: propTypes.bool.def(false) // 是否作为 sku 活动配置组件
})
const formData: Ref<Spu | undefined> = ref<Spu>() // 表单数据
const rules = ref()
const skuList = ref<Sku[]>([
  {
    price: 0, // 商品价格 零售价
    picUrl: '', // 图片地址
    appointSkusCount: {}, //关联商品
    expiryDate: undefined, //有效期
    expiryDateUnit: 1,
    friendTesyNum: '', //好友礼遇次数
    consumerMoney: undefined, //积分规则 消费多少元
    consumerPoints: undefined, //积分规则 积多少分
    rechargeMoney: undefined, //积分规则 充值多少元
    rechargePoints: undefined, //积分规则 积多少分
    memberMonthlyCouponType: 0, //付费会员|月赠送券设置类型 0 统一设置 1 单一设置
    bonusPoints: 0, //赠送积分
    isPostageCost: false, //是否包邮
    tabsName: '' as any, //标签卡名称
    typeDiscountGoods: [] as any, //指定商品类型
    useDiscountType: [] as any, //储值卡 使用折扣类型
    allDiscount: 0, //全部商品折扣
    appointTypeDiscount: {}, //指定商品类型
    appointSkusDiscount: {}, // 指定商品规则
    appointSkusCoupon: {}, //指定优惠券数量
    appointSkusBirthdayCoupon: {} //指定生日券数量

    // monthlyGiveCoupon: [
    //   {
    //     intoAccountDateDay: 1,
    //     skuCoupon: []
    //   }
    // ]
  }
]) // 批量添加时的临时数据
/** 规则 */
const giveGoodsruleConfig: RuleConfig[] = [
  {
    name: 'productConfig.discount',
    rule: (arg) => arg > 0,
    message: '赠送商品数量不能为 0 ！！！'
  }
] //赠送商品规则
const goodsDiscountruleConfig: RuleConfig[] = [
  {
    name: 'productConfig.discount',
    rule: (arg) => arg > 0,
    message: '商品折扣比例不能 空 ！！！'
  }
] //商品抵扣规则
/** 月赠送券类型*/
const monthGiveTypeChange = (item) => {
  // item.monthlyGiveCoupon = [
  //   {
  //     intoAccountDateDay: 1,
  //     intoAccountDateMonth: '',
  //     skuCoupon: []
  //   }
  // ]
}
/** 设置规则优惠券-赠送时 */
const GiveCouponSelectRef = ref()
const setRuleCoupon = () => {
  if (isEmpty(GiveCouponSelectRef.value)) {
    return
  }

  GiveCouponSelectRef.value?.forEach((item) => item.setGiveCouponList())
}
/** 设置生日券优惠券-赠送时 */
const GiveBrithdayCouponSelectRef = ref()
const setBrithdayRuleCoupon = () => {
  if (isEmpty(GiveBrithdayCouponSelectRef.value)) {
    return
  }

  GiveBrithdayCouponSelectRef.value?.forEach((item) => item.setGiveCouponList())
}

// const monthGiveTypeDelete = (couponList, tableIndex) => {
//   if (tableIndex == 0) {
//     message.warning('单一设置必须保留一项')
//     return
//   }
//   couponList.splice(tableIndex, 1)
// }
const monthGiveRollDateOptions = computed(() => {
  const arr = [] as EmptyArrayType
  for (let i = 1; i <= 31; i++) {
    arr.push({
      label: i,
      value: i
    })
  }
  return arr
})

/** 校验商品属性属性值 */
const validateProperty = () => {
  // 校验商品属性属性值是否为空，有一个为空都不给过
  const warningInfo = '存在属性属性值为空，请先检查完善属性值后重试！！！'
  for (const item of props.propertyList) {
    if (!item.values || isEmpty(item.values)) {
      message.warning(warningInfo)
      throw new Error(warningInfo)
    }
  }
}

const tableHeaders = ref<{ prop: string; label: string }[]>([]) // 多属性表头
// 关联商品校验信息
const giveGoodsFormErrorInfo = ref('')
const GiveGoodsFormRef = ref()
const discountGiveGoodsFormRef = ref()
const setgiveGoodsFormErrorInfo = (errorInfo) => {
  if (errorInfo) {
    giveGoodsFormErrorInfo.value = errorInfo
  } else {
    giveGoodsFormErrorInfo.value = errorInfo
  }
}
/**
 * 保存时，每个商品规格的表单要校验下。例如说，销售金额最低是 0.01 这种。
 */

const validateSku = async () => {
  try {
    validateProperty()
    let warningInfo = '请检查商品各行相关属性配置，'
    let validate = true // 默认通过
    if (!isEmpty(GiveGoodsFormRef?.value)) {
      for (const ele of GiveGoodsFormRef?.value) {
        if (!ele) {
          return
        }
        try {
          await ele.validate()
        } catch (error) {
          throw new Error(warningInfo)
        }
      }
    }
    if (!isEmpty(discountGiveGoodsFormRef?.value)) {
      for (const ele of discountGiveGoodsFormRef?.value) {
        if (!ele) {
          return
        }
        try {
          await ele.validate()
        } catch (error) {
          throw new Error(warningInfo)
        }
      }
    }

    await setRuleCoupon() //设置优惠券
    await setBrithdayRuleCoupon() //设置生日券

    for (const sku of formData.value!.skus!) {
      // 作为活动组件的校验
      for (const rule of props?.ruleConfig) {
        const arg = getValue(sku, rule.name)
        if (!rule.rule(arg)) {
          validate = false // 只要有一个不通过则直接不通过
          warningInfo += rule.message
          break
        }
      }
      // 只要有一个不通过则结束后续的校验
      if (!validate) {
        message.warning(warningInfo)
        throw new Error(warningInfo)
      }
    }
  } catch (error) {
    throw new Error(error + '')
  }
}
const getValue = (obj, arg) => {
  const keys = arg.split('.')
  let value = obj
  for (const key of keys) {
    if (value && typeof value === 'object' && key in value) {
      value = value[key]
    } else {
      value = undefined
      break
    }
  }
  return value
}

const emit = defineEmits<{
  (e: 'selectionChange', value: Sku[]): void
}>()
const objectToArray = (obj) => {
  return Object.keys(obj).map(function (key) {
    return { typeId: key, discount: obj[key].discount }
  })
}

const arrayToObject = (arr) => {
  return arr.reduce(function (obj, item) {
    obj[item.typeId] = {
      discount: item.discount
    }
    return obj
  }, {})
}
/**  商品类型 */
const SpuTypeSelectRef = ref()
const typeDiscount = ref<any>([])
const typeDiscountGoodsChange = (value, index) => {
  typeDiscount.value = []
  value.forEach((item) => {
    const row = {
      typeId: item,
      discount: 100
    }
    typeDiscount.value.push(row)
  })
  if (JSON.stringify(formData.value!.skus![index].appointTypeDiscount) != '{}') {
    // 如果有输入的值就回显
    let arr = objectToArray(formData.value!.skus![index].appointTypeDiscount)

    arr.forEach((element) => {
      typeDiscount.value.forEach((ele) => {
        if (ele.typeId == element.typeId) ele.discount = element.discount
      })
    })
  } else {
  }
  formData.value!.skus![index].appointTypeDiscount = arrayToObject(typeDiscount.value)
}
/**
 *
 * @param value
 * @param index  表示sku的index
 */
const getSputTypeInfo = (value, index) => {
  if (!value) {
    return
  }
  let text = ''
  let panelList = SpuTypeSelectRef.value[index].getCheckedNodes()
  // return panelList.find((ele) => {
  //   return ele.value == value
  // })
  panelList.filter((panelItem) => {
    if (panelItem.value == value) {
      text = panelItem.text
    }
  })
  return text
  // return info
}
/**
 * 将传进来的值赋值给 skuList
 */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) return

    formData.value = data
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.propFormRules,
  (data) => {
    if (!data) return
    rules.value = data
  },
  {
    deep: true,
    immediate: true
  }
)

/** 生成表数据 */
const generateTableData = (propertyList: any[]) => {
  // 构建数据结构
  const propertyValues = propertyList.map((item) =>
    item.values.map((v: any) => ({
      propertyId: item.id,
      propertyName: item.name,
      valueId: v.id,
      valueName: v.name
    }))
  )
  const buildSkuList = build(propertyValues)
  // 如果回显的 sku 属性和添加的属性不一致则重置 skus 列表
  if (!validateData(propertyList)) {
    // 如果不一致则重置表数据，默认添加新的属性重新生成 sku 列表
    formData.value!.skus = []
  }
  for (const item of buildSkuList) {
    const row = {
      properties: Array.isArray(item) ? item : [item], // 如果只有一个属性的话返回的是一个 property 对象
      price: 0, // 商品价格 零售价
      picUrl: '', // 图片地址
      appointSkusCount: [], //关联商品
      expiryDate: undefined, //有效期
      expiryDateUnit: 1,
      friendTesyNum: '', //好友礼遇次数

      consumerMoney: undefined, //积分规则 消费多少元
      consumerPoints: undefined, //积分规则 积多少分
      rechargeMoney: undefined, //积分规则 充值多少元
      rechargePoints: undefined, //积分规则 积多少分
      memberMonthlyCouponType: 0, //付费会员|月赠送券设置类型 0 统一设置 1 单一设置
      bonusPoints: 0, //赠送积分
      isPostageCost: false, //是否包邮
      // monthlyGiveCoupon: [
      //   {
      //     intoAccountDateDay: 1,
      //     skuCoupon: []
      //   }
      // ],
      tabsName: '' as any, //标签卡名称
      typeDiscountGoods: [] as any, //指定商品类型
      useDiscountType: [] as any, //储值卡 使用折扣类型
      allDiscount: 0, //全部商品折扣
      appointTypeDiscount: {}, //指定商品类型
      appointSkusDiscount: {}, //储值卡 指定商品规则
      appointSkusCoupon: {}, //指定优惠券数量
      appointSkusBirthdayCoupon: {}, //指定生日券数量
      bonusDays: 1, //月赠送券日期
      skuId: generateNumericUUID() //前端自定义生成的skuId
    }

    // 设置el-tab-pane 对应的属性 直接关联到sku上
    row.tabsName = row.properties[0].valueName

    // 如果存在属性相同的 sku 则不做处理
    const index = formData.value!.skus!.findIndex(
      (sku) => JSON.stringify(sku.properties) === JSON.stringify(row.properties)
    )
    if (index !== -1) {
      continue
    }
    formData.value!.skus!.push(row)
  }
}

/**
 * 生成 skus 前置校验
 */
const validateData = (propertyList: any[]) => {
  const skuPropertyIds: number[] = []
  formData.value!.skus!.forEach((sku) =>
    sku.properties
      ?.map((property) => property.propertyId)
      ?.forEach((propertyId) => {
        if (skuPropertyIds.indexOf(propertyId!) === -1) {
          skuPropertyIds.push(propertyId!)
        }
      })
  )
  const propertyIds = propertyList.map((item) => item.id)
  return skuPropertyIds.length === propertyIds.length
}

/** 构建所有排列组合 */
const build = (propertyValuesList: Property[][]) => {
  if (propertyValuesList.length === 0) {
    return []
  } else if (propertyValuesList.length === 1) {
    return propertyValuesList[0]
  } else {
    const result: Property[][] = []
    const rest = build(propertyValuesList.slice(1))
    for (let i = 0; i < propertyValuesList[0].length; i++) {
      for (let j = 0; j < rest.length; j++) {
        // 第一次不是数组结构，后面的都是数组结构
        if (Array.isArray(rest[j])) {
          result.push([propertyValuesList[0][i], ...rest[j]])
        } else {
          result.push([propertyValuesList[0][i], rest[j]])
        }
      }
    }
    return result
  }
}

/** 监听属性列表，生成相关参数和表头 */
watch(
  () => props.propertyList,
  (propertyList: PropertyAndValues[]) => {
    // 如果不是多规格则结束
    if (!formData.value!.specType) {
      return
    }
    // 如果当前组件作为批量添加数据使用，则重置表数据
    if (props.isBatch) {
      skuList.value = [
        {
          price: 0, // 商品价格 零售价
          picUrl: '', // 图片地址
          appointSkusCount: {}, //关联商品
          expiryDate: undefined, //有效期
          friendTesyNum: '', //好友礼遇次数

          expiryDateUnit: 1,
          consumerMoney: undefined, //积分规则 消费多少元
          consumerPoints: undefined, //积分规则 积多少分
          rechargeMoney: undefined, //积分规则 充值多少元
          rechargePoints: undefined, //积分规则 积多少分
          memberMonthlyCouponType: 0, //付费会员|月赠送券设置类型 0 统一设置 1 单一设置
          bonusPoints: 0, //赠送积分
          isPostageCost: false, //是否包邮
          bonusDays: 1 //月赠送券日期

          // monthlyGiveCoupon: [
          //   {
          //     intoAccountDateDay: 1,
          //     skuCoupon: []
          //   }
          // ]
        }
      ]
    }

    // 判断代理对象是否为空
    if (JSON.stringify(propertyList) === '[]') {
      return
    }
    // 重置表头
    tableHeaders.value = []
    // 生成表头
    propertyList.forEach((item, index) => {
      // name加属性项index区分属性值
      tableHeaders.value.push({ prop: `name${index}`, label: item.name })
    })
    // 如果回显的 sku 属性和添加的属性一致则不处理
    if (validateData(propertyList)) {
      return
    }
    // 添加新属性没有属性值也不做处理
    if (propertyList.some((item) => !item.values || isEmpty(item.values))) {
      return
    }
    // 生成 table 数据，即 sku 列表
    generateTableData(propertyList)
  },
  {
    deep: true,
    immediate: true
  }
)

// 暴露出生成 sku 方法，给添加属性成功时调用
defineExpose({ generateTableData, validateSku })
</script>
